package org.example.rowing.controller;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import lombok.extern.slf4j.Slf4j;
import org.example.rowing.controller.util.BaseController;
import org.example.rowing.controller.util.NavigationUtil;
import org.example.rowing.domain.RegistrationWithAthlete;
import org.example.rowing.enums.BoatTypeEnum;
import org.example.rowing.service.RaceInfoService;
import org.example.rowing.service.RegistrationInfoService;
import org.example.rowing.vo.EventVO;
import org.example.rowing.vo.RaceVO;
import org.example.rowing.vo.RegistrationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;


@Controller
@Slf4j
public class CKRegistrationInfoController extends BaseController {

    @FXML
    public VBox sideNav;
    @FXML
    public ComboBox<RaceVO> raceComboBox;
    public ComboBox<String> boatTypeComboBox;
    @FXML
    private TextField searchTextField;
    @FXML
    private TableView<RegistrationVO> eventsTable;
    @FXML
    public TableColumn<RegistrationVO, String> idColumn;
    @FXML
    private TableColumn<RegistrationVO, String> nameColumn;
    @FXML
    public TableColumn<RegistrationVO, String> athleteNumColumn;
    @FXML
    public TableColumn<RegistrationVO, String> teamNameColumn;
    @FXML
    public TableColumn<RegistrationVO, String> athleteNamesColumn;
    @FXML
    private TableColumn<RegistrationVO, Void> operationColumn;

    private ObservableList<RegistrationVO> eventList;

    @FXML
    public Button btnCKRegistration;
    @FXML
    private Button addCKRegistrationButton;
    @FXML
    public Button exportCKChooseButton;

    @Autowired
    private RegistrationInfoService registrationInfoService;
    @Autowired
    private RaceInfoService raceInfoService;

    @Override
    public void initialize() {
        super.initialize();

        // 设置表格列
        idColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getRegistrationId().toString()));
        nameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getRace().getName()));
        athleteNumColumn.setCellValueFactory(cellData -> {
            RegistrationVO vo = cellData.getValue();
            List<RegistrationWithAthlete> athletes = vo.getAthletes();
            if (athletes == null || athletes.isEmpty()) {
                return new SimpleStringProperty("");
            }
            // 提取每个选手的 athleteNum 并用逗号拼接
            String athleteNums = athletes.stream()
                    .map(RegistrationWithAthlete::getAthleteNum)
                    .collect(Collectors.joining(", "));
            return new SimpleStringProperty(athleteNums);
        });
        teamNameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getTeam().getName()));
        athleteNamesColumn.setCellValueFactory(cellData -> {
            RegistrationVO vo = cellData.getValue();
            List<RegistrationWithAthlete> athletes = vo.getAthletes();
            if (athletes == null || athletes.isEmpty()) {
                return new SimpleStringProperty("");
            }
            // 提取每个选手的 athleteNum 并用逗号拼接
            String athleteNames = athletes.stream()
                    .map(RegistrationWithAthlete::getAthleteName)
                    .collect(Collectors.joining(", "));
            return new SimpleStringProperty(athleteNames);
        });

        // 设置操作列（修改、删除按钮）
        operationColumn.setCellFactory(col -> new TableCell<>() {
            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    Button modifyButton = new Button("修改");
                    modifyButton.setOnAction(event -> handleModifyEvent(getTableRow().getItem()));

                    Button deleteButton = new Button("删除");
                    deleteButton.setOnAction(event -> handleDeleteEvent(getTableRow().getItem()));

                    HBox hBox = new HBox(modifyButton, deleteButton);
                    setGraphic(hBox);
                }
            }
        });

        // 设置转换器，使下拉框只显示 name
        raceComboBox.setConverter(new StringConverter<RaceVO>() {
            @Override
            public String toString(RaceVO raceVO) {
                return raceVO == null ? "" : raceVO.getId() + ". " + raceVO.getName();
            }
            @Override
            public RaceVO fromString(String string) {
                // 一般不需要转换回对象，可返回 null 或自行实现
                return null;
            }
        });

        // 初始化赛事列表（默认展示一些数据）
        // 级联选择
        List<String> boatTypes = List.of("皮艇", "划艇");
        boatTypeComboBox.setItems(FXCollections.observableArrayList(boatTypes));

        boatTypeComboBox.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                List<RaceVO> raceVOS = raceInfoService.showRacesByBoatType(newValue);
                raceComboBox.setItems(FXCollections.observableArrayList(raceVOS));
                // 自动选中第一个项目（如果存在）
                if (!raceVOS.isEmpty()) {
                    raceComboBox.getSelectionModel().select(0);
                }
            }
        });
        // 为下拉框添加监听器，用户选择其他赛事时更新表格数据
        raceComboBox.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                updateTableForRace(newValue);
            }
        });
        // 若需要在初始时就加载数据，可以先选中第一个赛事类型
        boatTypeComboBox.getSelectionModel().select(0);
    }

    private void updateTableForRace(RaceVO raceVO) {
        // 将过滤后的列表更新到表格
        eventList = FXCollections.observableArrayList(registrationInfoService.showRegistrationsByRaceId(raceVO.getId()));
        eventsTable.setItems(eventList);
        eventsTable.refresh();
    }

    @Override
    protected Button getButton() {
        return btnCKRegistration;
    }

    // 搜索事件
    @FXML
    public void handleSearch() {
        String teamNameQuery = searchTextField.getText().trim();

        log.info("搜索栏内容为：{}", teamNameQuery);

        RegistrationVO registration = new RegistrationVO();
        registration.setRaceId(raceComboBox.getSelectionModel().getSelectedItem().getId());
        if (!teamNameQuery.isEmpty()) {
            registration.setTeamName(teamNameQuery);
        }

        // 将过滤后的列表更新到表格
        eventList.setAll(registrationInfoService.showSearchedRegistrations(registration));
        eventsTable.refresh();
    }

    @FXML
    public void handleClearSearch() {
        // 清空搜索框内容
        searchTextField.clear();

        // 重新显示所有赛事
        eventList.setAll(registrationInfoService.showRegistrationsByRaceId(raceComboBox.getSelectionModel().getSelectedItem().getId()));
        eventsTable.refresh();
    }

    // 添加赛事事件
    @FXML
    public void handleAddEvent() {
        // 打开添加赛事界面的逻辑
        log.info("点击添加赛事按钮");
        NavigationUtil.showPopup(
                NavigationUtil.viewMap.get(addCKRegistrationButton.getId()),
                "报名信息",
                addCKRegistrationButton.getScene().getWindow(),
                controller -> {
                    if (controller instanceof UpdateCKRegistrationController) {
                        ((UpdateCKRegistrationController) controller).initialize(null);
                    }
                }
        );
        // 刷新展示内容
        eventList.setAll(registrationInfoService.showRegistrationsByRaceId(raceComboBox.getSelectionModel().getSelectedItem().getId()));
        eventsTable.refresh();
    }

    // 修改赛事事件
    public void handleModifyEvent(RegistrationVO registrationVO) {
        // 进行修改赛事操作
        log.info("修改报名信息: {}", registrationVO.getRegistrationId());
        NavigationUtil.showPopup(
                NavigationUtil.viewMap.get(addCKRegistrationButton.getId()),
                "修改赛事",
                eventsTable.getScene().getWindow(),
                controller -> {
                    if (controller instanceof UpdateCKRegistrationController) {
                        ((UpdateCKRegistrationController) controller).initialize(registrationVO);
                    }
                }
        );
        // 刷新展示内容
        eventList.setAll(registrationInfoService.showRegistrationsByRaceId(raceComboBox.getSelectionModel().getSelectedItem().getId()));
        eventsTable.refresh();
    }

    // 删除赛事事件
    public void handleDeleteEvent(RegistrationVO registrationVO) {
        Optional<ButtonType> result = showConfirmationDialog();
        // 删除赛事操作
        if (result.isPresent() && Objects.equals(result.get().getText(), "确定")) {
            registrationInfoService.deleteRegistration(registrationVO.getRegistrationId());
            log.info("删除报名信息: {}", registrationVO.getRace().getName());
            // 刷新展示内容
            eventList.setAll(registrationInfoService.showRegistrationsByRaceId(raceComboBox.getSelectionModel().getSelectedItem().getId()));
            eventsTable.refresh();
        } else {
            log.info("取消删除");
        }
    }

    @FXML
    public void handleNavButtonClick(ActionEvent event) throws IOException {
        log.info("当前触发事件为：{}",event);
        Button clickedButton = (Button) sideNav.getScene().getFocusOwner();
        NavigationUtil.navigateToScene(
                event,
                NavigationUtil.viewMap.get(clickedButton.getId()),
                "皮划艇管理");
    }

    @FXML
    public void handleRowingClick(ActionEvent event) throws Exception {
        log.info("切换到赛艇界面");
        NavigationUtil.navigateToScene(
                (Stage) sideNav.getScene().getWindow(),
                "/fxml/rowingViews/EventInfoView.fxml",
                "赛艇管理");
    }

    @FXML
    public void handleExportChooseEvent(ActionEvent event) {
        // 打开添加赛事界面的逻辑
        log.info("开始选择导出项目");
        NavigationUtil.showPopup(
                NavigationUtil.viewMap.get(exportCKChooseButton.getId()),
                "选择导出确认单的队伍",
                exportCKChooseButton.getScene().getWindow(),
                controller -> {
                    if (controller instanceof CKRegistrationExportController) {
                        ((CKRegistrationExportController) controller).initialize(null);
                    }
                }
        );
    }
}
